$(function() {
    var collectProductionName = JSON.parse(localStorage.getItem('collectProductionName'));
    // 本地存储去重
    for (let i = 0; i < collectProductionName.length - 1; i++) {
        for (let j = i + 1; j < collectProductionName.length; j++) {
            if (collectProductionName[i].title == collectProductionName[j].title) {
                collectProductionName.splice(j, 1);
                j--;
            }
        }
    }
    localStorage.setItem('collectProductionName', JSON.stringify(collectProductionName));

    var collect = [];
    var count = 0;
    getJson(collect, count, collectProductionName); // 向页面填充数据
})

// 向页面填充数据
function getJson(collect, count, collectProductionName) {
    $.get('data/goods.json', function(response) {
        for (key in response.goods) {
            for (let i = 0; i < collectProductionName.length; i++) {
                if (response.goods[key].title == collectProductionName[i].title) {
                    collect[count++] = response.goods[key];
                }
            }
        }
        var table = document.querySelector('.products');
        var strHTML = ``;
        for (var i = 0; i < collect.length; i++) {
            strHTML += `<tr>
                <td><input name="product" type="checkbox" value="${i}" /></td>
                <td><img src="${collect[i].imgPath}" alt="alt" /></td>
                <td>${collect[i].title}</td>
                <td>${collect[i].shop}</td>
                <td>${collect[i].price} </td>
                <td class="del">删除</td>
                        </tr>`;
        }
        table.innerHTML = strHTML;
        checkOnclick(collect); //全选按钮与复选按钮
        // console.log(collect);

        //点击删除按钮，删除本地存储数据
        var delIndex = -1; //需要删除的行的索引
        $('.del').click(function() {
            delIndex = $('.del').index($(this));
            this.parentNode.parentNode.removeChild(this.parentNode);
            collect.splice(delIndex, 1);
            collectProductionName.splice(delIndex, 1);
            localStorage.setItem('collectProductionName', JSON.stringify(collectProductionName));
            // console.log(collect);
        })
    })
}

//全选按钮与复选按钮
function checkOnclick(collect) {
    var all = document.getElementById('all');
    var products = document.getElementsByName('product');
    var sum = 0;
    all.onclick = function() {
        for (let i = 0; i < products.length; i++) {
            products[i].checked = all.checked;
        }
        if (all.checked) {
            sum = products.length;
        } else {
            sum = 0;
        }
    }
    for (let i = 0; i < collect.length; i++) {
        products[i].onclick = function() {
            this.checked == true ? sum++ : sum--;
            if (sum == collect.length) {
                all.checked = true;
            } else {
                all.checked = false;
            }
        }
    }
}